<?php
namespace Admin\Controller;
use Admin\Controller\ApplyController;
/**
 * 部门管理
 */
class GroupController extends AdminController{

	/**
	 * 部门列表
	 * huying Dec 29, 2015
	 */
	public function index()
	{
		/*$where = '1 = 1';
		$where .= I('get.name') ? ' and name like "%' . I('get.name') . '%"' : '';
		$where .= I('get.status', -1) > -1 ? ' and status =' . I('get.status') : '';
		$list = $this->getList('id,name,aids,status', 'group', $where, 'id desc', true);
		$this->assign('list', $list);
		$this->display();*/
		$where = '1 = 1';
		$list = $this->getList('*', 'group', $where,'id asc');
		foreach($list as $key => $value)
		{
			if($value['pid'] == 0)
			{
				$arr[] = $value;
				foreach($list as $k => $v)
				{
					if($v['pid'] == $value['id'])
					{
						$arr[] = $v;
						foreach($list as $k1 => $v1)
						{
							if($v1['pid'] == $v['id'])
							{
								$arr[] = $v1;
							}
						}
					}
				}
			}
		}
		$this->assign('list', $arr);
		$this->display();
	}

	/**
	 * 添加列表
	 * huying Dec 29, 2015
	 */
	public function add()
	{
		if(IS_POST)
		{
			$data=array(
				'name'        => $_POST['name'],
				'status'      => $_POST['status'],
				'remark'      => $_POST['remark'],
				'pid'         => $_POST['pid'],
				'type'        => $_POST['type'],
				'note'        => $_POST['note'],
				'work_status' => $_POST['work_status'],
				);
			$result = $this->updateData($data, 'group');
			//$this->returnResult($result);
			$this->returnResult($result, null, U('Group/rule', array('id' => $result)));
		}else{
			$list = $this->getList('*', 'group', 'status=1', 'id asc');
			foreach($list as $key => $value)
			{
				if($value['pid'] == 0)
				{
					$arr[] = $value;
					foreach($list as $k => $v)
					{
						if($v['pid'] == $value['id'])
						{
							$arr[] = $v;
						}
					}
				}
			}
			$this->assign('nodeList', $arr);
			$this->display();
		}
	}

	/**
	 * 修改部门
	 * huying Dec 29, 2015
	 */
	public function edit()
	{
		if(IS_POST)
		{
			$data=array(
               'name'=>$_POST['name'],
               'status'=>$_POST['status'],
               'remark'=>$_POST['remark'],
               'pid'=>$_POST['pid'],
               'type'=>$_POST['type'],
               'work_status'=>$_POST['work_status'],
			);
			$result=M('group')->where('id='.I('get.id', 0, 'intval'))->save($data);
			$this->returnResult($result);
			//$result = $this->updateData($data, 'group', 2);
			//$this->returnResult($result, null, U('Group/rule', array('id' => $_POST['id'])));
		}else{
			$info = $this->getInfo('*', 'group', 'id=' . I('get.id', 0, 'intval'));
			$this->assign('info', $info);
			$list = $this->getList('*', 'group', 'status=1','id asc');
			foreach($list as $key => $value)
			{
				if($value['pid'] == 0)
				{
					$arr[] = $value;
					foreach($list as $k => $v)
					{
						if($v['pid'] == $value['id'])
						{
							$arr[] = $v;
						}
					}
				}
			}
			$this->assign('nodeList', $arr);
			$this->display('add');
		}
	}

	/**
	 * 权限分配
	 * huying Dec 29, 2015
	 */
	public function rule()
	{
		if(IS_POST)
		{
			$_POST['rules'] = implode(',', $_POST['rule']);
			$result = $this->updateData($_POST, 'group', 2);
			$this->returnResult($result);
		}else{
			$list = $this->getList('id,pid,title,name,type,sort,status', 'node', 'status=1', 'sort desc,id asc');
			foreach($list as $key => $value)
			{
				if($value['pid'] == 0)
				{
					$arr[] = $value;
					foreach($list as $k => $v)
					{
						if($v['pid'] == $value['id'])
						{
							$arr[] = $v;
							foreach($list as $k1 => $v1)
							{
								if($v1['pid'] == $v['id'])
								{
									$arr[] = $v1;
								}
							}
						}
					}
				}
			}
			$this->assign('list', $arr);
			$info = $this->getInfo('id,rules', 'group', 'id=' . I('get.id', 0, 'intval'));
			$info['rules'] = explode(',', $info['rules']);
			$this->assign('info', $info);
			$this->display();
		}
	}

	/**
	 * 删除部门
	 * huying Dec 29, 2015
	 */
	public function del()
	{
		$id = I('get.id', 0, 'intval');
		if($id == 1)
		{
			$this->returnResult(false, array('', '默认部门不可删除'));
		}
		$num = M('admins')->where(array('gid' => $id))->count();
		if($num > 0)
		{
			$this->returnResult(false, array('', '当前部门内有员工存在，不可删除'));
		}
		$result = M('group')->where('id=' . $id)->setField('status', 2);
		$result = $this->deleteData('id=' . $id, 'group');
		$this->returnResult($result);
	}

	//完善部门详情
	public function addInfo()
	{
		$group_id=I('get.id',0,'intval');
		$info=$this->getInfo('*','group_info','group_id='.$group_id);
		$info['product_line']=explode(',',$info['product_line']);
		$address=new ApplyController();
		if($info)
		{

           $now_areaInfo = $address->getAreaInfo($info['area_id']);
		}else{

		   $now_areaInfo = $address->getAreaInfo();
		}

        $this->assign('group_id',$group_id);
		$this->assign('info',$info);
	    $this->assign('now_areaInfo', $now_areaInfo);
		$this->display();
	}

	public function edit_groupInfo()
	{

            $data = array(
				'group_id'            => $_POST['group_id'],
				'place_name'          => $_POST['place_name'],//渠道名称
				// 'area_id'          =>$address->getAreaIDByPCD($_POST['now_district'],$_POST['now_city'],$_POST['now_province']),
				'communicate_address' => $_POST['communicate_address'],
				'communicate_tel'     => $_POST['tel'],
				'principal_name'      => $_POST['principal_name'],
				'email'               => $_POST['email'],
				'company_account'     => $_POST['account_one'],
				'company_bank'        => $_POST['bank_one'],
				'company_account2'    => $_POST['account_two'],
				'company_bank2'       => $_POST['bank_two'],
				'settle_type'         => $_POST['settle_type'],
				'business_area'       => $_POST['area'],
				'model'               => $_POST['model'],
				'ratio'               => $_POST['ratio'],
				'ticket_cost'         => $_POST['ticket_cost'],
				'rate_max'            => $_POST['rate_max'],
				'rate_min'            => $_POST['rate_min'],
				'settle_rate'         => $_POST['settle_rate'],
				'rebate_max'          => $_POST['rebate_max'],
				'my_risk_ratio'       => $_POST['my_risk_ratio'],
				'place_risk_ratio'    => $_POST['place_risk_ratio'],
				'product_line'        => implode(',',$_POST['product_line']),
				'easy_credit_max'     => $_POST['easy_max'],
				'performance_money'   => $_POST['performance_money'],
				'gearing_ratio'       => $_POST['gearing'],
				'deposit_max'         => $_POST['deposit'],
				'times'               => time(),
				'status'              => 1,
				'num'                 => 1
            	);
           // $ass=new ApplyController();
		    $data['area_id'] = $this->getAreaIDByPCD($_POST['now_district'],$_POST['now_city'],$_POST['now_province']);
            // echo $data['area_id'];
            // exit;
			$upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize   = 3145728 ;// 设置附件上传大小
			$upload->exts      = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
			$upload->rootPath  = './Uploads/'; // 设置附件上传根目录
			$upload->savePath  = ''; // 设置附件上传（子）目录
			// 上传文件
			$info   =   $upload->upload();
			if ($info)
			{
				// 上传成功 获取上传文件信息
			    foreach($info as $uploadKey => $file)
			    {
			    	$data[$uploadKey] = "http://".$_SERVER['HTTP_HOST']."/Uploads/".$file['savepath'].$file['savename'];
			    }
			}
			 if($_POST['id']!='')
			 {
              $result=M('group_info')->where('id='.$_POST['id'])->save($data);
            }else{
            	$result=M('group_info')->add($data);
            }

            if($result)
            {
              redirect('/Admin/Group/index');
            }else{
            	$this->error('操作失败',U('Group/index'),0);
            }
	}

	public function getAreaIDByPCD($p_district = null,$p_city = null,$p_province = null)
	{
		$tmp_areaID = 110000;
		if ($p_district)
		{
			$tmp_areaID = $p_district;
		}else if ($p_city) {
			$tmp_areaID = $p_city;
		}else{
			$tmp_areaID = $p_province;
		}

		return $tmp_areaID;
	}

//通讯录
	public function Address_Book()
	{
		$where='1=1';
		$where.=' and a.group_id=b.id';
		$where .= I('get.user_name') != '' ? ' and a.name like "%'.I('get.user_name').'%"' : '';
		$where .= I('get.telephone') != '' ? ' and a.tel = '.I('get.telephone') : '';
		$where .= I('get.create_time_beg') != '' ? ' and a.add_time >= '.strtotime(I('get.create_time_beg')) : '';
		$where .= I('get.create_time_end') != '' ? ' and a.add_time < '.strtotime(I('get.create_time_end')) : '';
		$list=$this->getList('a.*,b.name as group_name',array('address_book a','group b'),$where,'id desc',true);
		$this->assign('list',$list);
		$this->display();
	}
//通讯录添加
	public function Book_add()
	{
		$group=$this->getList('*','group','status=1 and work_status=1');
		$this->assign('group',$group);
		$this->display();
	}
//通讯录修改
	public function Book_edit()
	{
		if(IS_POST)
		{
          $data = array(
			'post'     => $_POST['post'],
			'group_id' => $_POST['group_id'],
			'name'     => $_POST['name'],
			'tel'      => $_POST['tel'],
			'email'    => $_POST['email'],
			'status'   => 1,
          	);
          if($_POST['id']!='')
          {
          	 $data['update_time']=time();
             $result=M('address_book')->where('id='.$_POST['id'])->save($data);
          }else{
          	 $data['add_time']=time();
          	 $data['update_time']=time();
             $result=M('address_book')->add($data);
          }
          if($result)
          {
            redirect('/Admin/Group/Address_Book');
          }else{
          	$this->error('操作失败');
          }
		}else{
            $group=$this->getList('*','group','status=1 and work_status=1');
            $bookInfo=$this->getInfo('*','address_book','id='.I('get.id',0,'intval'));
            $this->assign('bookInfo',$bookInfo);
			$this->assign('group',$group);
			$this->display('Book_add');
		}
	}
//抵押备案人
		public function Mortgagee()
		{
		$where='1=1';
		$where.=' and a.group_id=b.id';
		$where .= I('get.user_name') != '' ? ' and a.name like "%'.I('get.user_name').'%"' : '';
		$where .= I('get.telephone') != '' ? ' and a.tel = '.I('get.telephone') : '';
		$where .= I('get.create_time_beg') != '' ? ' and a.add_time >= '.strtotime(I('get.create_time_beg')) : '';
		$where .= I('get.create_time_end') != '' ? ' and a.add_time < '.strtotime(I('get.create_time_end')) : '';
		$list=$this->getList('a.*,b.name as group_name',array('mortgagee a','group b'),$where,'id desc',true);
		$this->assign('list',$list);
		$this->display();
	}
//抵押备案人添加
	public function Mortgagee_add()
	{
		$group=$this->getList('*','group','status=1 and work_status=1');
		$this->assign('group',$group);
		$this->display();
	}
//抵押备案人修改
	public function Mortgagee_edit()
	{
		if(IS_POST)
		{
          $data=array(
            'post'=>$_POST['post'],
            'group_id'=>$_POST['group_id'],
            'name'=>$_POST['name'],
            'tel'=>$_POST['tel'],
            'email'=>$_POST['email'],
            'status'=>1,
          	);
          if($_POST['id']!='')
          {
          	 $data['update_time']=time();
             $result=M('mortgagee')->where('id='.$_POST['id'])->save($data);
          }else{
          	 $data['add_time']=time();
          	 $data['update_time']=time();
             $result=M('mortgagee')->add($data);
          }
          if($result)
          {
            redirect('/Admin/Group/Mortgagee');
          }else{
          	$this->error('操作失败');
          }
		}else{
            $group=$this->getList('*','group','status=1 and work_status=1');
            $bookInfo=$this->getInfo('*','mortgagee','id='.I('get.id',0,'intval'));
            $this->assign('bookInfo',$bookInfo);
			$this->assign('group',$group);
			$this->display('Mortgagee_add');
		}
	}
}